/*
 * 文件名称: CookieUtils.java Copyright 2011-2015 Ximalaya All right reserved.
 */
package top.zxybird.common.util;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.Cookie;

import top.zxybird.common.model.Position;

/**
 * @author cossea
 */
public final class CookieUtils {
  public final static String LOGIN_TOKEN = "_token";
  public final static String YES = "y";
  private final static String rememberToken = YES;
  public final static String REMEMBER_ME = "remember_me";

  public final static String LOGIN_COOKIE_KEY = "_token";
  public final static String DEVICE_COOKIE_KEY = "_device";
  public final static String APP_CHANNEL_KEY = "channel";
  public final static String APP_BUNDLE_KEY = "impl";
  public final static String DEVICE_MAC_KEY = "XUM";

  /**
   * 位置信息，post请求会带
   */
  public final static String POSITION_KEY = "NSUP";
  public final static String OLD_POSITION_KEY = "SUP";
  public final static String SYMBOL_AND = "&";
  public final static String SYMBOL_DOT = ",";

  /**
   * 测试用|兼容老版本。url中带公共参数的
   */
  public static String PARAM_UID = "uid";
  public static String PARAM_TOKEN = "token";
  public static String PARAM_BUNDLE_ID = "bundleId";
  public static String PARAM_CHANNEL_ID = "channelId";
  public static String PARAM_VERSION = "version";
  public static String PARAM_DEVICE_ID = "deviceId";
  public static String PARAM_DEVICE = "device";
  public static String PARAM_POSITIONX = "positionx";
  public static String PARAM_POSITIONY = "positiony";
  public static String PARAM_MAC = "mac";
  public static String PARAM_SCALE = "scale";

  /**
   * 从cookie中解析登录token
   */
  public static String getLoginToken(String environmentId, Cookie[] cookies) {
    String loginToken = null;
    String loginTokenKey = getLoginTokenKey(environmentId);
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookie.getName().equals(loginTokenKey)) {
          loginToken = cookie.getValue();
        }
      }
    }
    return loginToken;
  }

  /**
   * 从cookie中解析渠道名称
   */
  public static String parseChannel(Cookie[] cookies) {
    String channel = null;
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (APP_CHANNEL_KEY.equals(cookie.getName())) {
          channel = cookie.getValue();
          break;
        }
      }
    }
    return channel;
  }

  /**
   * 从cookie中解析渠道名称
   */
  public static String parseImpl(Cookie[] cookies) {
    String impl = null;
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (APP_BUNDLE_KEY.equals(cookie.getName())) {
          impl = cookie.getValue();
          break;
        }
      }
    }
    return impl;
  }

  /**
   * 从cookie中解析出地理位置信息
   * <P>
   * <li>SUP是旧版本的地理位置key
   * <li>NSUP是新版本的地理位置key
   */
  public static Position parsePosition(Cookie[] cookies) {
    Position position = null;
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (POSITION_KEY.equals(cookie.getName())) {
          String value = cookie.getValue();
          try {
            value = java.net.URLDecoder.decode(value, "UTF-8");
          } catch (UnsupportedEncodingException e) {
            // pass
          }
          String[] split = value.split(SYMBOL_DOT);
          if (split.length == 3) {
            String lngValue = split[0];
            String latValue = split[1];
            String tsValue = split[2];
            double lng = (double) Float.intBitsToFloat(Long.valueOf(lngValue, 16).intValue());
            double lat = (double) Float.intBitsToFloat(Long.valueOf(latValue, 16).intValue());
            long ts = Long.valueOf(tsValue);
            position = new Position(lng, lat, ts);
          }
          break;
        } else if (OLD_POSITION_KEY.equals(cookie.getName())) {
          String value = cookie.getValue();
          try {
            value = java.net.URLDecoder.decode(value, "UTF-8");
          } catch (UnsupportedEncodingException e) {
            // pass
          }
          String[] split = value.split(SYMBOL_DOT);
          if (split.length == 3 || split.length == 2) {
            String lngValue = split[0];
            String latValue = split[1];
            double lng = Double.valueOf(lngValue);
            double lat = Double.valueOf(latValue);
            long ts = 0;
            if (split.length == 3) {
              String tsValue = split[2];
              ts = Long.valueOf(tsValue);
            } else {
              ts = System.currentTimeMillis();
            }
            position = new Position(lng, lat, ts);
          }
          break;
        }
      }
    }
    return position;
  }

  public static boolean isRemeberMe(String environmentId, Cookie[] cookies) {
    boolean rememberMe = false;
    String rememberMeKey = getRememberMeKey(environmentId);
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookie.getName().equals(rememberMeKey)) {
          rememberMe = rememberToken.equals(cookie.getValue());
        }
      }
    }
    return rememberMe;
  }

  private static String getLoginTokenKey(String environmentId) {
    StringBuilder key = new StringBuilder();
    key.append(environmentId).append(SYMBOL_AND).append(LOGIN_TOKEN);
    return key.toString();
  }

  private static String getRememberMeKey(String environmentId) {
    StringBuilder key = new StringBuilder();
    key.append(environmentId).append(SYMBOL_AND).append(REMEMBER_ME);
    return key.toString();
  }
}
